//
//  YWDoKeepWatchMissionTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/8/12.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWDoKeepWatchMissionTableViewController.h"
#import "Masonry.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"

#import "YWWriteNoteCell.h"
#import "YWTakePhotoCell.h"
#import "YWRuleTableViewCell.h"
#import "YWPostTroubleInfoCell.h"
#import "YWLocationCell.h"
#import "UITableView+FDTemplateLayoutCell.h"

//#import "YWImageView.h"
#import "YWPhotoView.h"
#import "YWPostTroubleTableViewController.h"
#import "MBProgressHUD.h"
//#import "YWAlertView.h"
#import "YWShowPostTroubleInfoTableViewController.h"

#import "YWPatrollineRecord.h"
#import "YWKeepWatchMissionManager.h"
#import "YWEquipment.h"
#import "YWLocationManager.h"
#import "YWEquipmentManager.h"
#import "YWMissionManager.h"
#import "YWNotifyManager.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWReportTroubleModel.h"
#import "YWReportTroubleManager.h"

@interface YWDoKeepWatchMissionTableViewController () <YWTakePhotoCellDelegate,YWPostTroubleVCDelegate,clickCancelThePostTroubleMissionDelegate,YWWriteNoteCellDelegate>
//@property (nonatomic, strong) UIView * headView;
@property (nonatomic, copy) NSString * locationString;
@property (nonatomic, weak) MBProgressHUD* HUD;
//定位位置
@property (nonatomic, strong) CLLocation* clMapLocation;
//巡更位置对比，是否超过20米
@property (nonatomic, assign) BOOL isOverLocation;

//巡更项数组
@property (nonatomic, strong) NSArray * keepWatchRuleResults;
//巡更内容
@property (nonatomic, strong) NSString * keepWatchRuleContent;

@property (nonatomic, strong) NSString *note;

//报障
@property (nonatomic, strong) UIButton * myTroublesButton;
//提交
@property (nonatomic, strong) UIButton * submitButton;

@property (nonatomic, strong) UIView * footView;
//任务拍照图片数组
@property (nonatomic, strong) NSArray * totalImageNameArray;

//报障设备记录数组
@property (nonatomic, strong) NSMutableArray * postTroubleRecordArray;
@end

@implementation YWDoKeepWatchMissionTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"keepWatch", nil);
    _locationString = NSLocalizedString(@"positioning", nil);
    
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    [self.tableView registerClass:[YWTakePhotoCell class] forCellReuseIdentifier:YWTakePhotoCellIdentifier];
    [self.tableView registerClass:[YWLocationCell class] forCellReuseIdentifier:YWLocationCellIdentifier];
    
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = self.footView;
    
    self.tableView.estimatedRowHeight = 90.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self location];
    
//    //测试很多点的巡更
//    YWPatrollineRecord *lineRecord = nil;
//    NSString *uniqueTag = [YWCommonTool uniqueTagWithMission:_keepWatchMission];
//    
//    if (_tempPatrolLineRecord) {
//        lineRecord = _tempPatrolLineRecord;
//    }else{
//        if (uniqueTag.length == 0) {
//            [YWCommonTool showTextHUDWithContent:@"当前不是工作时间"];
//            return;
//        }
//        lineRecord = [[YWKeepWatchMissionManager shareManager] latestPatrollineRecordWithUniqueTag:uniqueTag];
//        
//    }
//    if (lineRecord == nil) {
//        //新建looper
//        lineRecord = [[YWKeepWatchMissionManager shareManager] createLooperRecordWith:_keepWatchMission uniqueTag:uniqueTag];
//    }
//    NSArray *allPoint = [[YWKeepWatchMissionManager shareManager] allPatrolLocationWithPatrolLineId:self.keepWatchMission.patrolLine.patrolLineId];
//    [allPoint enumerateObjectsUsingBlock:^(YWPatrolLineLocationRel*  _Nonnull rel, NSUInteger idx, BOOL * _Nonnull stop) {
//        self.locationId = rel.locationId;
//        YWPatrolPointRecord* record = [self createPatrolPointRecord:lineRecord];
//        [[YWKeepWatchMissionManager shareManager] updatePatrolPointRecordWithArray:@[ record ]];
//    }];
    
}

- (NSArray *)keepWatchRuleResults
{
    if (!_keepWatchRuleResults) {
        NSMutableArray *patrolLineIds = [NSMutableArray array];;
        [patrolLineIds addObject:[NSString stringWithFormat:@"%ld",(long)self.keepWatchMission.patrolLine.patrolLineId]];
        NSArray *keepWatchRuleResults = [[YWKeepWatchMissionManager shareManager] patrolLocationNoteWithLocationId:self.locationId lineIds:patrolLineIds];
        _keepWatchRuleResults = keepWatchRuleResults;
    }
    return _keepWatchRuleResults;
}

- (NSString *)keepWatchRuleContent{
    if (!_keepWatchRuleContent) {
        NSMutableString *content = [NSMutableString string];
        [self.keepWatchRuleResults enumerateObjectsUsingBlock:^(YWPatrolLineLocationRel* _Nonnull locationRel, NSUInteger idx, BOOL* _Nonnull stop) {
            NSString *note = [NSString stringWithFormat:@"%lu.%@", (unsigned long)idx + 1, locationRel.note ?: NSLocalizedString(@"none", nil)];
            if (idx!=0) {
                [content appendString:@"\n"];
            }
            [content appendString:note];
        }];
        _keepWatchRuleContent = content.length>0?[NSString stringWithFormat:@"%@",content]:NSLocalizedString(@"none", nil);
    }
    return _keepWatchRuleContent;
}

#pragma mark - tableViewHeaderView

- (void)location
{
    //[[YWLocationManager shareManager] setUpLocationAccuracy:kCLLocationAccuracyNearestTenMeters];
    BOOL enable = [CLLocationManager locationServicesEnabled];
    int status = [CLLocationManager authorizationStatus];
    if (enable && (status == kCLAuthorizationStatusAuthorizedWhenInUse)) {
        [[YWLocationManager shareManager] locationInfoWithCompletionBlock:^(NSString* locationInfo, NSError* error, CLLocation* location) {
            dispatch_async(dispatch_get_main_queue(), ^{
                _locationString = locationInfo;
                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
                self.clMapLocation = location;
                
                YWLog(@"%@",location);
                NSArray *equipmentArray = nil;
                if (self.qrcodeId) {
                    equipmentArray = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:self.qrcodeId];
                }else if (self.locationId){
                    equipmentArray = [[YWEquipmentManager shareManager] equipmentWithLocationId:self.locationId];
                }
                
                YWEquipment *eqipment = equipmentArray.count?equipmentArray[0]:nil;
                NSString *coordinate = eqipment.coordinate?:@"";
                NSArray *coordinateArray = [coordinate componentsSeparatedByString:@","];
                if (coordinateArray.count>=2) {
                    CLLocation* current = [[CLLocation alloc] initWithLatitude:[[coordinateArray firstObject] doubleValue] longitude:[[coordinateArray lastObject] doubleValue]];
                    CLLocationDistance meters = [self.clMapLocation distanceFromLocation:current];
                    self.isOverLocation = meters > 20 ? true : false;
                }
            });
        }];
    }
    else if (status == kCLAuthorizationStatusDenied) {
        _locationString = NSLocalizedString(@"accessLocationsAreNotAllowed", nil);
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
    }
    else if (!iOS8 && (!enable || status < 3)) {
        [[YWLocationManager shareManager] locationInfoWithCompletionBlock:^(NSString* locationInfo, NSError* error, CLLocation* location) {
            _locationString = locationInfo;
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        }];
    }
}

//- (UIView *)headView{
//    if (!_headView) {
//        UIView * headView = [[UIView alloc] init];
//        headView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 44);
//        //位置图片
//        UIImageView* locationImageV = [[UIImageView alloc] init];
//        [headView addSubview:locationImageV];
//        [locationImageV mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.bottom.mas_equalTo(headView).offset(0);
//            make.left.mas_equalTo(headView).offset(10);
//            make.size.mas_equalTo(CGSizeMake(24, 24));
//        }];
//        locationImageV.image = [UIImage imageNamed:@"common_location"];
//        //位置
//        UILabel* locationLabel = [[UILabel alloc] init];
//        [headView addSubview:locationLabel];
//        [locationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.mas_equalTo(locationImageV.mas_right).offset(10);
//            make.bottom.mas_equalTo(headView).offset(0);
//        }];
//        locationLabel.font = KTitleFont;
//        locationLabel.numberOfLines = 2;
//        _headView = headView;
//    }
//    return _headView;
//}

#pragma mark - tableViewFootView

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 100);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH/2-20*2;
        //      报障
        _myTroublesButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _myTroublesButton.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        _myTroublesButton.layer.masksToBounds = YES;
        _myTroublesButton.layer.cornerRadius = 5.0;
        
        [_myTroublesButton setTitle:NSLocalizedString(@"postTrouble", nil) forState:UIControlStateNormal];
        [_myTroublesButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _myTroublesButton.backgroundColor = [UIColor customRedColor];
        [_myTroublesButton addTarget:self action:@selector(cliclPostTroubleEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:_myTroublesButton];
        //      提交
        _submitButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _submitButton.frame = CGRectMake(20*2+_myTroublesButton.bounds.size.width+20, 30, buttonWidth, kButtonH);
        _submitButton.layer.masksToBounds = YES;
        _submitButton.layer.cornerRadius = 5.0;
        
        [_submitButton setTitle:NSLocalizedString(@"commit", nil) forState:UIControlStateNormal];
        [_submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _submitButton.backgroundColor = [UIColor customBlueColor];
        [_submitButton addTarget:self action:@selector(clickCommintButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:_submitButton];
    }
    return _footView;
}

#pragma mark - table View sectionHeadView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section ==0 ) {
        return nil;
    }
    static NSString* HeaderIdentifier = @"YWDoKeepWatchMissionTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
    
}

-(NSString *)titleForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return nil;
    }else if (section==1){
        return NSLocalizedString(@"keepWatchItem", nil);//@"巡更项";
    }else if (section==2){
        return NSLocalizedString(@"note", nil);//@"备注";
    }else if (section==3){
        return NSLocalizedString(@"postTroubleEquipment", nil);//@"报障设备";
    }else{
        return NSLocalizedString(@"takePhotoToUpload", nil);//@"拍照上传";
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return section==0 ?0.01 : 35;
}


#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0) {
        return UITableViewAutomaticDimension;
        //[tableView fd_heightForCellWithIdentifier:YWLocationCellIdentifier cacheByIndexPath:indexPath configuration:^(YWLocationCell *cell) {
//            cell.locationText = _locationString?:@"";
//        }];
    }else if (indexPath.section == 1) {
        return UITableViewAutomaticDimension;//[YWRuleTableViewCell cellHeightOfRuleContent:self.keepWatchRuleContent];
    }else if (indexPath.section == 2){
        return 90;
    }else if (indexPath.section == 3){
        //报障设备
        return _postTroubleRecordArray.count>0 ? 54 : 44;
    }else{
        CGFloat imageH = YWPhotoSize*(_totalImageNameArray.count/4+1) + YWPhotoGap*(_totalImageNameArray.count/4);
        return 10*2 + imageH;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 3) {
        return _postTroubleRecordArray.count?:1;
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        YWLocationCell * cell = [tableView dequeueReusableCellWithIdentifier:YWLocationCellIdentifier];
        cell.locationText = _locationString?:@"";
        return cell;
    }else if (indexPath.section == 1){
        YWRuleTableViewCell *cell = [YWRuleTableViewCell cellWithTableView:tableView];
        cell.ruleContent = self.keepWatchRuleContent;
        return cell;
    }else if (indexPath.section == 2){
        YWWriteNoteCell * cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.textViewPlaceHolder = NSLocalizedString(@"writeSomethingElse", nil);
        cell.delegate = self;
        return cell;
    }else if (indexPath.section == 3){
        YWPostTroubleInfoCell *cell = [YWPostTroubleInfoCell cellWithTableView:tableView];
        YWReportTroubleModel *reportTroubel = _postTroubleRecordArray.count>0?_postTroubleRecordArray[indexPath.row]:nil;
        cell.reportTrouble = reportTroubel;
        return cell;
    }else{
        YWTakePhotoCell * cell = [tableView dequeueReusableCellWithIdentifier:YWTakePhotoCellIdentifier];
        cell.delegate = self;
        cell.totalImageNameArray = self.totalImageNameArray;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==3) {
        YWReportTroubleModel *reportTrouble = _postTroubleRecordArray.count>0?_postTroubleRecordArray[indexPath.row]:nil;
        if (reportTrouble) {
            YWShowPostTroubleInfoTableViewController *showPostTroubleVC = [[YWShowPostTroubleInfoTableViewController alloc] init];
            showPostTroubleVC.reportTrouble = reportTrouble;
            showPostTroubleVC.delegate = self;
            [self.navigationController pushViewController:showPostTroubleVC animated:YES];
        }
    }
}

#pragma mark - clickCancelThePostTroubleMissionDelegate
- (void)clickCancelTheReportTrouble:(YWReportTroubleModel*)reportTrouble{
    if ([_postTroubleRecordArray containsObject:reportTrouble]) {
        [[YWReportTroubleManager shareManager] deleteReportTroubleWithTroubleId:reportTrouble.troubleId orUniqueTag:reportTrouble.uniqueTag];
        [_postTroubleRecordArray removeObject:reportTrouble];
        [self.tableView reloadData];
    }
}

#pragma mark - YWTakePhotoCellDelegate
-(void)resetCellFrameWithImages:(NSArray *)images cell:(UITableViewCell *)cell{
    NSArray* arr = [[NSArray alloc] initWithArray:images copyItems:YES];
    self.totalImageNameArray = arr;
    [self.tableView reloadData];
}

#pragma mark - YWPostTroubleVCDelegate
- (void)passBackReportTrouble:(YWReportTroubleModel *)reportTrouble{
    //报修记录
    if (!_postTroubleRecordArray) {
        _postTroubleRecordArray = [NSMutableArray array];
    }
    if (reportTrouble) {
        [_postTroubleRecordArray addObject:reportTrouble];
        [self.tableView reloadData];
    }
}
#pragma mark - YWWriteNoteCellDelegate
- (void)passNote:(NSString *)note{
    _note = note;
}
#pragma mark - buttonAction
- (void)cliclPostTroubleEvent:(UIButton *)sender{
    [self.view endEditing:YES];
    //报障
    NSArray* allEquipmentArray = nil;
    if (self.qrcodeId) {
        allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:self.qrcodeId];
    }else if (self.locationId){
        allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithLocationId:self.locationId];
    }
    YWPostTroubleTableViewController * postTroublevc = [[YWPostTroubleTableViewController alloc] init];
    postTroublevc.currentEquipment = allEquipmentArray.count ? allEquipmentArray[0] : nil;
    postTroublevc.equipmentArray = allEquipmentArray;
    postTroublevc.qrCodeId = _qrcodeId;
    postTroublevc.locationId = _locationId;
    postTroublevc.shouldPopBack = YES;
    postTroublevc.delegate = self;
    [self.navigationController pushViewController:postTroublevc animated:YES];
}

- (void)clickCommintButtonEvent:(UIButton *)sender{
    [self.view endEditing:YES];
    if ([YWCommonTool isContainsEmoji:_note]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (_note.length > 100) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
        return;
    }
    if (_isOverLocation) {
        NSString *tipString = NSLocalizedString(@"currentLocationMaybeWrong", nil);
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"warning", nil) message:tipString preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self readyToCommit];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self readyToCommit];
    }
}

- (void)readyToCommit{
    //完成提交
    NSString* tipString = _postTroubleRecordArray.count>0 ? NSLocalizedString(@"commitRecordWithTrouble", nil) : NSLocalizedString(@"commitRecordWithoutTrouble", nil);
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:tipString preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.HUD show:YES];
        [self commitRecord];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)commitRecord{
    YWPatrollineRecord *lineRecord = nil;
    NSString *uniqueTag = [YWCommonTool uniqueTagWithMission:_keepWatchMission];
    
    if (_tempPatrolLineRecord) {
        lineRecord = _tempPatrolLineRecord;
    }else{
        if (uniqueTag.length == 0) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"thisMomentIsNotWorkTime", nil)];
            return;
        }
        lineRecord = [[YWKeepWatchMissionManager shareManager] latestPatrollineRecordWithUniqueTag:uniqueTag];
        
    }
    if (lineRecord == nil) {
        //新建looper
        lineRecord = [[YWKeepWatchMissionManager shareManager] createLooperRecordWith:_keepWatchMission uniqueTag:uniqueTag];
    }
    
    YWPatrolPointRecord* record = [self createPatrolPointRecord:lineRecord];
    BOOL saveRecord = [[YWKeepWatchMissionManager shareManager] updatePatrolPointRecordWithArray:@[ record ]];
    NSArray* pictures = [self createPicturesWithPatrolPointRecord:record];
    BOOL savePicturesToDB = [[YWKeepWatchMissionManager shareManager] updatePatrolPictureWithArray:pictures];
    BOOL updatePatrolLineRecord = NO;
    if (saveRecord) {
        lineRecord.count += 1;
        NSArray* totalPoint = [[YWKeepWatchMissionManager shareManager] allPatrolLocationWithPatrolLineId:lineRecord.patrolLineId];
        if (record.status == YWPatrolpointRecordStatusTrouble) {
            lineRecord.result = YWPatrollineRecordResultUnfinishAndTrouble;
        }
        if (lineRecord.count == 1) {
            lineRecord.startTime = record.patrolTime;
        }
        //lineRecord.patrolLineId==0 是做临时巡更
        if (lineRecord.count == totalPoint.count || lineRecord.patrolLineId==0) {
            if (lineRecord.result == YWPatrollineRecordResultUnfinishAndTrouble) {
                lineRecord.result = YWPatrollineRecordResultFinishAndTrouble;
            }
            else {
                lineRecord.result = YWPatrollineRecordResultFinishAndNormal;
            }
        }
        lineRecord.endTime = record.patrolTime;
        updatePatrolLineRecord = [[YWKeepWatchMissionManager shareManager] updatePatrollineRecordWithArray:lineRecord ? @[ lineRecord ] : nil];
    }
    
    if (saveRecord && savePicturesToDB && updatePatrolLineRecord && record) {
        [self.HUD hide:YES];
        //报障与记录的关系
        [self.postTroubleRecordArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTrouble, NSUInteger idx, BOOL * _Nonnull stop) {
            [[YWMissionManager shareManager] saveRecordAndPostTroubleRelWithtroubleId:reportTrouble.troubleId detailUniqueTag:record.detailUniqueTag];
        }];
        
        [[YWKeepWatchMissionManager shareManager] startUploadRecord:record pictures:pictures];
        
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextSubmitPatrolRecordSuccess, nil)];

        [[YWNotifyManager shareManager] postReflashPatrolLineViewNotify];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissSelfView];
        });
    }
    else {
        [self.HUD hide:YES];
        YWLog(@"保存数据库失败");
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextSubmitPatrolRecordFail, nil)];
    }
}

- (YWPatrolPointRecord*)createPatrolPointRecord:(YWPatrollineRecord*)patrolLineRecord
{
    YWPatrolPointRecord* record = [[YWPatrolPointRecord alloc] init];
    record.patrolLineId = patrolLineRecord.patrolLineId;
    record.uniqueTag = patrolLineRecord.uniqueTag;
    record.patrolpointRecordId = [NSString stringWithFormat:@"%@_%ld", patrolLineRecord.uniqueTag, (long)self.locationId];
    record.status = _postTroubleRecordArray.count>0 ? YWPatrolpointRecordStatusTrouble : YWPatrolpointRecordStatusNormal;
    record.detailUniqueTag = record.patrolpointRecordId;
    record.keepWatchMissionId = patrolLineRecord.keepWatchMissionId;
    record.locationId = self.locationId;
    record.sort = [[YWKeepWatchMissionManager shareManager] sortWithLocationId:record.locationId patrolLineId:record.patrolLineId];
    NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970] * 1000;
    record.patrolTime = nowTime;
    
    record.note = _note;
    record.uploadStatus = YWPatrolPointRecordUploadStatusUploading;
    YWHandler *hander = [[YWHandler alloc] init];
    hander.uniqueId = [YWLoginTool loginUser].uniqueId;
    record.executor = hander;
    record.posTroubleArray = self.postTroubleRecordArray;
    return record;
}

- (NSArray*)createPicturesWithPatrolPointRecord:(YWPatrolPointRecord*)record
{
    NSMutableArray* pictures = [NSMutableArray array];
    for (int i = 0; i < [self.totalImageNameArray count]; i++) {
        YWPatrolPicture* picture = [[YWPatrolPicture alloc] init];
        picture.recordId = record.patrolpointRecordId;
        picture.pictureId = [YWCommonTool randStringId];
        picture.pictureName = self.totalImageNameArray[i];
        picture.isLocalImage = YES;
        picture.uploadStatus = YWPictureRecordUploadStatusNull;
        picture.recordType = YWPictureRecordTypePatrol;
        [pictures addObject:picture];
    }
    return pictures;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextSubmitTask, nil);
        hud.dimBackground = YES;
        // hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)dismissSelfView
{
    if (self.isFromLedger) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

- (void)dealloc{
    [[YWLocationManager shareManager] cancelLocationServer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
